<?php
/**
 * 攀枝花市智慧人社就医服务中间件
 *
 *
 * @author wangwh
 */

namespace Pzhrs\Controller;

class PzhMedicalTestControlController
{
    // SoapClient 对象
    private $soap = FALSE;

    // 记录是否为正式环境
    private $isFormal = FALSE;

    //是否开启缓存
    private static $CACHE = false;

    // 医疗机构科室列表缓存建
    private static $CACHE_INSTITUTION_CLASS_LIST = 'CACHE_INSTITUTION_CLASS_LIST';


    static $URL_API = 'http://220.166.60.252:8083/wxjk.dll/wsdl/Iwxjk';//http://192.168.203.55:8078/HisService.asmx?WSDL
    static $back_URL_API = "http://localhost:8081/";

    //医院id
    private $hospitalId;

    //自助机id
    private $userId;

    /**
     * 构造函数
     */
    function __construct()
    {
        header('Content-Type: text/html; charset=utf-8');
        $this->hospitalId = 75;
        if (!method_exists($this, ACTION_NAME)) {
            $function = ACTION_NAME;
            A('Receive')->$function();
        }
    }

    public function xml_to_array($list){
        $ob= simplexml_load_string($list);
        $json  = json_encode($ob);
        $configData = json_decode($json, true);
        return $configData;
    }

    public $hospitalKey = array(
        "75" => "7daf7603429012aeae417fa9beed9c75",
    );
    //正式地址
    //	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    //	static $version = "2.2.7";
    //	private $token = "6a2967e64a994e54b533aa7942328179";
    //正式地址


    // 	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    /**
     * 请求His API
     *
     *   使用SoapClient请求HIS webservice接口
     *
     * @param String $Flag 类型
     * @param String $Content xml请求内容
     * @param String $Result_K 返回xml中的跟节点key
     *
     * @return array
     */


    private function soapGetDate($Flag, $Content)
    {
//        $this->isFormal = ($_SERVER['SERVER_NAME']!="localhost" && "histest.mobimedical.cn"!=$_SERVER['SERVER_NAME']);
        $this->isFormal = false;

        if (!$this->soap) {
            $this->soap = new \SoapClient(self::$URL_API, array("connection_timeout" => 15));
        }
        try {

            /* 正式环境 */
            if ($this->isFormal) {
                //专线接口,走平台
                try {
                    $result = $this->soap->Weixin($Content);
                } catch (\Exception $e) {
                    $fileContent = $Content . "\n" . $e->getMessage();
                    $dir = "soapGetDate/";
                    \Org\Util\File::createDir($dir);
                    file_put_contents($dir . $Flag . "_error.txt", $fileContent);
                    return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试21！");
                }
                $Result_K = "Weixin" . Result;

                /* 测试环境 */
            } else {
                $result = $this->soap->$Flag( $Content);
                /* 记录请求日志   */
                $fileContent = $Content . "\r" . var_export($result, true);
                $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
                $filename = date("H_i_s") . "_" . rand(10000, 99999);
                writeLog($dir, $filename, $fileContent);

                return json_decode(json_encode(json_decode(json_encode((array)simplexml_load_string(substr($result, 54)), true))), true);
            }


        } catch (\Exception $e) {
            /* 记录请求异常日志  */
            $fileContent = $Content . "\n" . $e->getMessage();
            $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
            $filename = date("H_i_s") . "_error";
            writeLog($dir, $filename, $fileContent);
            return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试22！");
            exit;
        }
    }


    function Post($url, $method, $post = null)
    {
        if (is_array($post)) {
            ksort($post);
            $content = http_build_query($post);
            $content_length = strlen($content);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' =>
                        "Content-type: application/x-www-form-urlencoded; charset=utf-8\r\n" .
                        "Content-length: $content_length\r\n",
                    'content' => $content
                )
            );
            $res = file_get_contents($url, false, stream_context_create($options));
            $fileContent = var_export($post, true) . "\r" . var_export($res, true) . "\r" . var_export(json_decode($res, true), true);
            $dir = "soapGetDateXt/" . date("Y-m-d") . "/" . $method . "/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
            return $res;
        }
    }

    /**
     * 中间件签名验证
     * @param array $params
     * @return string
     */
    function middelEnCodeSign($params)
    {
        ksort($params);
        $preString = "";
        $time = $params['time'];
        $hospitalId = $params['hospitalId'];
        foreach ($params as $k => $v) {
            if ($k == 'time' || $k == 'sign' || !$v)
                continue;
            $preString .= $k . "=" . $v;
        }

        $keyString = $this->hospitalKey[$hospitalId];
        //加密
        return sha1($preString . $keyString . $time);
    }


    /**
     * 确认病人信息  绑卡
     * @param $car_no '就诊卡号'
     * @param $user_name '病人姓名'
     */
    public function cardInfoQuery()
    {
//        $sign       = $this->middelEnCodeSign($_POST);
//        if($sign!=$_POST['sign']){
//            echo "签名不正确";exit;
//        }
        $card_no    = $_POST['identy_id'];
        $user_name  = $_POST['user_name'];

        //$card_no = '600143066';

        $Content ="<HIS><card_no>".$card_no."</card_no></HIS>";

        $searchKey = "patient";
        $result = $this->soapGetDate($searchKey, $Content);
        if ($result['status'] == 0 && !empty($result['data']['name'])) {
            if ($result['data']['name'] == $user_name && $result['status'] == 0) {
                $returnArr['status'] = 1;
                $returnArr['errorMsg'] = "绑卡成功";
                $returnArr['data'] = $result['Data'];
            } else {
                $returnArr['status'] = 2;
                $returnArr['errorMsg'] = "姓名输入有误";
                $returnArr['data'] = array();
            }

        } else {
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = $result['ResultMsg'];
            $returnArr['data'] = array();

        }

        echo json_encode($returnArr);
    }

    public function Test_jj()
    {
        //echo '122';die();
        //$client = new \SOAPClient('http://192.168.100.149:9192/OrderTreat/services/HosiptalManager?wsdl');
        $url='http://10.166.121.249:8089/xtpt/services/yinHaiBusiness?wsdl';
        $s=new \SoapClient($url);
        /*
         *SoapHeader参数说明如下所示:
         *'http://tempuri.org/'   namespace(命名空间可省略)
         *'MySoapHeader'          SoapHeader头的类名
         *'array(...)'            存放标识身份的字符串参数
         *'true'                  是否必须处理该header
        */
        $mmkj='http://yinhai.com';
        $code='yinhai@789'; //授权码
        $funNo='WX_001';    //交易编号 
        $xml_xx="<input><aac001>4000612523</aac001><startrow>1</startrow><endrow>3</endrow><inputxml><inputxml><aac002>510402198306076317</aac002><aac003>张帆</aac003></inputxml></inputxml></input>";
        $apiUrl='http://pzh.91cure.com/index.php?g=Home&m=Test&a=pzh_sign';
        $params1 = array();
        $params1['content']=$xml_xx;
        $xmlsing=$this->PostData_jm($apiUrl,$params1);

        $auth_header = array( "jybh" =>$funNo ,"systemKey" =>$code ,"source" =>$xml_xx,"signature" =>$xmlsing  );
        $authvalues = new \SoapVar($auth_header, SOAP_ENC_OBJECT,"system",$mmkj);  
        $u = new \SoapHeader($mmkj, 'system', $authvalues);
        $s->__setSoapHeaders($u);
        $params['inputxml']=$xml_xx;
        $suc=$s->callBusiness($params);
        $data=$suc->return;
        $tesres = $this->xml_to_array($data);
        dump($tesres);
    }
    //养老保险查询
    function EndowmentInsurance_Query(){
        $identyId='510402198306076317';   //身份证号码
        $name='张帆';       //姓名
        $funNo='WX_001';    //交易编号
        $xml="<input><aac001>4000612523</aac001><startrow>1</startrow><endrow>3</endrow><inputxml><inputxml><aac002>".$identyId."</aac002><aac003>".$name."</aac003></inputxml></inputxml></input>";
        $url='http://10.166.121.249:8089/xtpt/services/yinHaiBusiness?wsdl';
        $client=new \SoapClient($url);
        dump($xml);
        $result_list=$this->Get_service_api($xml,$funNo,$client);
        $datares=$result_list['output']['row'];
        if($result_list['code']=='1'){
            $returnArr['status'] = 1;
            $returnArr['errorMsg']=$result_list['message'];
            $returnArr['data']['name']=$name;                   //姓名
            $returnArr['data']['identyId']=$identyId;           //身份证号码
            $returnArr['data']['insured_units']=$datares['aab004'];     //参保所在单位名称
            $returnArr['data']['insured_status']=$datares['aac008'];    //参保状态
            $returnArr['data']['payment_status']=$datares['aac031'];    //缴费状态
            $returnArr['data']['payment_max_period']=$datares['aae002'];    //最大缴费期号
            $returnArr['data']['payment_total_local']=$datares['aic027'];   //在本地缴费总金额
            $returnArr['data']['payment_total_monthly']=$datares['aic079']; //累计缴费总月数
            $returnArr['data']['payment_total_money']=$datares['aic040'];   //截至当前个人账户累计存储额         
            //echo json_encode($returnArr);exit;
        }else{//格式化为标准接口模式
            $returnArr['status'] = 2;
            $returnArr['errorMsg'] = $result_list['message'];
        };
        dump($returnArr);
    }

    /**
     * 统一调接口方法 
     * $xml       接口传递的参数
     * $funNo     接口的方法名
     * $client    接口需要调用的webservice对象 
     * */
    function Get_service_api($xml,$funNo,$client){
        $mmkj='http://yinhai.com';
        $code='wx20170921'; //授权码
        //$apiUrl='http://pzh.91cure.com/index.php?g=Home&m=Test&a=pzh_sign';
        $apiUrl='http://127.0.0.1:442/index.php?g=Whszxyy&m=WhszxyyControlxin1&a=pzh_sign';
        $params1 = array();
        $params1['content']=$xml;
        $xmlsing=$this->PostData_jm($apiUrl,$params1);
        $auth_header = array( "jybh" =>$funNo ,"systemKey" =>$code ,"source" =>$xml,"signature" =>$xmlsing  );
        $authvalues = new \SoapVar($auth_header, SOAP_ENC_OBJECT,"system",$mmkj);  
        $u = new \SoapHeader($mmkj, 'system', $authvalues);
        $client->__setSoapHeaders($u);
        $params['inputxml']=$xml;
        $suc=$client->callBusiness($params);
        $data=$suc->return;
        $tesres = $this->xml_to_array($data);
        return  $tesres;
    }
    /**
     * 数字签名
     * $url         签名地址
     * $post        签名参数
     * */
    function PostData_jm($url, $post = null) {
        if (is_array($post)) {
            ksort($post);
            $rsaPrivateKeyPem='http://172.16.8.2:442/bcp.keystore';
            $content11 = htmlspecialchars_decode($post['content']);
            $priKey = file_get_contents($rsaPrivateKeyPem);  
            $res1 = openssl_pkey_get_private($priKey);
            openssl_sign($content11, $sign, $res1);
            openssl_free_key($res1);   
            $sign = bin2hex($sign);
            return $sign;
            //return $res;
        }
    }

    /**
     * 社保卡绑定与解绑
     * @param 
     */
    function GetTiedCard_Reg(){
        $identyId='510402198306076317';   //身份证号码
        $name='张帆';       //姓名
        $wx_openid='tcyl_222';      //第三方ID ‘tcyl_’加微信openid
        $phone='13127530852';          //电话2223988  13550908933
        $Card_no='D11718733x';        //社保卡卡号 D13825348 4000611622  D04016899
        $Trading_channels='01';   //交易渠道 渠道目前只有微信,请默认写01
        $Transaction_Type='2';   //交易类型 1-绑定,2-解绑
        $funNo='WX_010';    //交易编号
        //dump(C('URL_API'));die();
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901><aac002>".$identyId."</aac002><aac003>".$name."</aac003><aae005>".$phone."</aae005><akc020>".$Card_no."</akc020><yad961>".$Trading_channels."</yad961><yad941>".$Transaction_Type."</yad941></inputxml></inputxml></input>";
        dump($xml);//die();
        if($this->is_idcard($identyId))
        {
            $client=new \SoapClient(C('URL_API'));
            $result_list=$this->Get_service_api($xml,$funNo,$client);
            dump($result_list);
            if($result_list['code']=='1'){
                $returnArr['status'] = 1;
                $returnArr['errorMsg']=$result_list['message'];       
                //echo json_encode($returnArr);exit;
            }else{//格式化为标准接口模式
                $returnArr['status'] = 2;
                $returnArr['errorMsg'] = $result_list['message'];
            };
        } else {
            echo 'sfz不合法!';
            $returnArr['status'] = 3;
            $returnArr['errorMsg'] = '身份证号码输入不正确，请输入正确的身份证号码！';
        };//die();
        dump($returnArr);
        /* 记录请求日志   */
            $fileContent = var_export(json_encode($returnArr), true);
            $dir = "soapGetDate/" . date("Y-m-d") . "/WXsb_GetTiedCard_Regtt/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
        echo json_encode($returnArr);
    }

    /**
     * 科室信息
     * @param 
     */
    function GetDept(){
        $hospitalCode='525009'; //医院编码
        $deptCode='';       //科室编号
        $funNo='his001';    //交易编号
        //dump(C('URL_API'));die();
        $xml="<Request><deptCode>".$deptCode."</deptCode><functionid>".$funNo."</functionid><akb020>".$hospitalCode."</akb020></Request>";
        dump($xml);//die();

        //$client=new \SoapClient(C('URL_API'));
        $client='http://172.16.0.2:20309/xtpt/services/yinHaiBusiness?wsdl';
        $result_list=$this->Get_service_api($xml,$funNo,$client);
        dump($result_list);die();

        if($this->is_idcard($identyId))
        {
            $client=new \SoapClient(C('URL_API'));
            $result_list=$this->Get_service_api($xml,$funNo,$client);
            dump($result_list);
            if($result_list['code']=='1'){
                $returnArr['status'] = 1;
                $returnArr['errorMsg']=$result_list['message'];       
                //echo json_encode($returnArr);exit;
            }else{//格式化为标准接口模式
                $returnArr['status'] = 2;
                $returnArr['errorMsg'] = $result_list['message'];
            };
        } else {
            echo 'sfz不合法!';
            $returnArr['status'] = 3;
            $returnArr['errorMsg'] = '身份证号码输入不正确，请输入正确的身份证号码！';
        };//die();
        dump($returnArr);
        /* 记录请求日志   */
            $fileContent = var_export(json_encode($returnArr), true);
            $dir = "soapGetDate/" . date("Y-m-d") . "/WXsb_GetTiedCard_Regtt/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
        echo json_encode($returnArr);
    }

    

}
?>